﻿Public Class frmQuotationEntry
    Dim dbSystem As New dbSystem
    Dim dbSales As New dbSales
    Dim Var As New varDeclare
    Dim frmCtrl As New FormControl
    Dim curr2word As New Currency
    Dim dsBase As DataSet
    Dim dsItem As DataSet
    Dim dsCurr As DataSet
    Dim CurrBase As String
    Public EntryID As String
    Dim ca As String
    Dim dgvTemp As New DataGridView
    Dim dsCustomer As DataSet
    Dim TypeAct As String

    Private Sub GenerateField()
        dsCurr = dbSystem.CurrList(Var.CompID)
        If (dsCurr.Tables(0).Rows.Count > 0) Then
            For i = 0 To dsCurr.Tables(0).Rows.Count - 1
                Try
                    cbDocCurr.Items.Add(dsCurr.Tables(0).Rows(i)("ID").ToString().Trim())
                Catch ex As Exception
                End Try
            Next
        End If

        '' ComboBox Incoterms
        Dim Incoterms As New List(Of comboItem)
        Incoterms.Add(New comboItem("Ex-Works ITALY", "0"))
        Incoterms.Add(New comboItem("FOB", "1"))
        Incoterms.Add(New comboItem("CIF", "2"))
        Incoterms.Add(New comboItem("Delivered", "3"))
        cmbIncoterms.DataSource = Incoterms
        cmbIncoterms.DisplayMember = "Text"
        cmbIncoterms.ValueMember = "Value"

        '' ComboBox Transportation
        Dim Transportation As New List(Of comboItem)
        Transportation.Add(New comboItem("To be Confirmed", "X"))
        Transportation.Add(New comboItem("Airfreight", "A"))
        Transportation.Add(New comboItem("Seafreight", "B"))
        cmbTransportation.DataSource = Transportation
        cmbTransportation.DisplayMember = "Text"
        cmbTransportation.ValueMember = "Value"

        '' ComboBox Payment
        Dim Payment As New List(Of comboItem)
        Payment.Add(New comboItem("Cash on advance", "-1"))
        Payment.Add(New comboItem("Cash & Carry", "0"))
        Payment.Add(New comboItem("COD", "1"))
        cmbPayment.DataSource = Payment
        cmbPayment.DisplayMember = "Text"
        cmbPayment.ValueMember = "Value"

        '' ComboBox Salutaion
        Dim dtSalutation As DataTable = dbSystem.FreeQueryDataTable("SELECT TAB_TEXT ID FROM TABLE_VALUE WHERE TAB_TYPE = 'SALUTATION'")
        If (dtSalutation.Rows.Count > 0) Then
            For i = 0 To dtSalutation.Rows.Count - 1
                Try
                    cmbAttSolut.Items.Add(dtSalutation.Rows(i)("ID").ToString().Trim())
                Catch ex As Exception
                End Try
            Next
        End If
    End Sub

    Private Sub frmQuotationEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
        dsCustomer = New dbSystem().FreeQueryDataSet("SELECT [Code], [Company], [Term Day] FROM v_CustAccountList")
        advCustomer.Visible = False
        advCustomer.Initialize(dsCustomer, "Code", txtCustCode)
        txtPackingCost.Text = "0.00"
        txtDeliveryCost.Text = "0.00"
        GenerateField()
        dsItem = dbSales.GetItemList()
        cbDocCurr.Text = New dbSystem().FreeQueryString("SELECT TOP 1 CURR_BASE FROM CURRENCIES WITH(NOLOCK)")
        txtQuotationNumber.Text = EntryID
        dgvTemp.Columns.Add("clID", "clID")
        dgvTemp.Rows.Add(EntryID)
        ToolbarHeader1.DefaultRow = 1
        ToolbarHeader1.Iniliaze("Entry : Quotation", Me, New frmQuotationList, dgvTemp, "clID")
        If (EntryID = "") Then
            ToolbarHeader1.ActionCtrl(False, False, False, False, False, False, False, False, True)
            txtQuotationNumber.Text = dbSales.LastNumberQuotation(dtDocDate.Value.ToString("yyyy"))
            TypeAct = "I"
        Else
            ToolbarHeader1.ActionCtrl(True, False, True, False, True, False, False, True, True)
            TabControl1.Enabled = False
            dgvBase.ReadOnly = True
            dgvBase.ContextMenuStrip = Nothing
            Dim dtHeader As DataTable = New dbSystem().FreeQueryDataTable("SELECT * FROM v_QuotationList WHERE Number = '" & EntryID & "' AND COMP = '" & Var.CompID & "'")
            cbDocCurr.Text = dtHeader.Rows(0)("Curr").ToString().Trim()
            lblRev.Text = dtHeader.Rows(0)("REV").ToString().Trim()
            txtCustCode.Text = dtHeader.Rows(0)("Cust Code").ToString().Trim()
            txtOffice.Text = dtHeader.Rows(0)("OFFICE").ToString().Trim()
            'txtCustCompany.Text = dtHeader.Rows(0)("Customer").ToString().Trim()
            txtPhone.Text = dtHeader.Rows(0)("PHONE").ToString().Trim()
            txtFax.Text = dtHeader.Rows(0)("FAX").ToString().Trim()
            txtRef.Text = dtHeader.Rows(0)("REF").ToString().Trim()
            cmbAttSolut.Text = dtHeader.Rows(0)("SALUTATION").ToString().Trim()
            txtAttentionname.Text = dtHeader.Rows(0)("Client").ToString().Trim()
            cmbIncoterms.Text = dtHeader.Rows(0)("INCOTERMS").ToString().Trim()
            txtEmail.Text = dtHeader.Rows(0)("PRO_EMAIL").ToString().Trim()
            txtPaymentDay.Text = dtHeader.Rows(0)("TERMS").ToString().Trim()
            dtRef.Value = CDate(dtHeader.Rows(0)("REF_DATE").ToString().Trim())
            dtDocDate.Value = CDate(dtHeader.Rows(0)("Offer Date").ToString().Trim())
            dtValDate.Value = CDate(dtHeader.Rows(0)("Validity Date").ToString().Trim())
            TypeAct = "U"
            dsBase = dbSales.GetQuotationLine(EntryID)
            If (dsBase.Tables(0).Rows.Count() > 0) Then
                ca = "LOAD"
                dgvBase.Rows.Add(dsBase.Tables(0).Rows.Count)
                For i = 0 To dsBase.Tables(0).Rows.Count - 1
                    Try
                        dgvBase.Rows(i).Cells("clChoose").Value = dsBase.Tables(0).Rows(i)("ITEM").ToString().Trim()
                        dgvBase.Rows(i).Cells("clDesc").Value = dsBase.Tables(0).Rows(i)("IC_DESCRIPTION").ToString().Trim()
                        dgvBase.Rows(i).Cells("clPriceList").Value = dsBase.Tables(0).Rows(i)("PRO_UNIT_PRICE").ToString().Trim()
                        dgvBase.Rows(i).Cells("clDisc").Value = dsBase.Tables(0).Rows(i)("PRO_DISC").ToString().Trim()
                        dgvBase.Rows(i).Cells("clNetPrice").Value = dsBase.Tables(0).Rows(i)("PRO_NET_PRICE").ToString().Trim()
                        dgvBase.Rows(i).Cells("clUOM").Value = dsBase.Tables(0).Rows(i)("PRO_UOM").ToString().Trim()
                        dgvBase.Rows(i).Cells("clQty").Value = dsBase.Tables(0).Rows(i)("PRO_QTY").ToString().Trim()
                        dgvBase.Rows(i).Cells("clNetAmount").Value = dsBase.Tables(0).Rows(i)("PRO_AMOUNT").ToString().Trim()
                        dgvBase.Rows(i).Cells("clComment").Value = dsBase.Tables(0).Rows(i)("NOTES").ToString().Trim()
                        dgvBase.Rows(i).Cells("clDiscReal").Value = dsBase.Tables(0).Rows(i)("PRO_DISC").ToString().Trim()
                        dgvBase.Rows(i).Cells("clNetReal").Value = dsBase.Tables(0).Rows(i)("PRO_NET_PRICE").ToString().Trim()
                    Catch ex As Exception
                    End Try
                Next
                ca = "FINISH"
            End If
            Dim NeedApprove As Boolean = True
            Dim dtTransactionSales As DataTable = dbSales.TransactionSalesStatus(EntryID)
            Dim CustomerPO = dtTransactionSales.Rows(0)("CustomerPO").ToString()
            If (CustomerPO <> "") Then
                NeedApprove = False
                lblStatus.Text = "CLOSE"
                txtRef.Text = CustomerPO
                dtRef.Value = CDate(dtTransactionSales.Rows(0)("DateCustomerPO").ToString())
            End If
            ToolbarHeader1.tsApprove.Visible = NeedApprove
            ToolbarHeader1.tsEdit.Visible = NeedApprove
        End If
        SumSubTotal()
    End Sub

    Private Function validateForm() As Boolean
        Dim val As Boolean = True
        If (txtQuotationNumber.Text.Trim() = "" Or txtCustCompany.Text.Trim() = "" Or cbDocCurr.Text = "" Or txtDocRate.Text.Trim() = "" Or _
            txtRef.Text.Trim() = "" Or cmbIncoterms.Text = "") Then
            val = False
        End If
        If (val) Then
            If (ckbExworks.Checked) Then
                If (cmbTransportation.Text = "" Or txtPackingCost.Text.Trim() = "" Or txtDeliveryCost.Text.Trim() = "" Or txtPaymentDay.Text.Trim() = "" Or _
                    cmbPayment.Text = "" Or txtWeight.Text.Trim = "" Or txtVolume.Text.Trim()) Then
                    val = False
                End If
            End If
        End If
        If (val = False) Then MessageBox.Show("Please Check All Field With Star Mark (*)")
        Return val
    End Function

    ''================================== Control Header ==============================================''
    Private Sub tsNew_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsNewClick
        Dim OpenForm As New frmQuotationEntry
        OpenForm.EntryID = ""
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsEdit_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsEditClick
        TypeAct = "U"
        ToolbarHeader1.ActionCtrl(False, False, False, False, False, True, True, False, True)
        dgvBase.ReadOnly = False
        TabControl1.Enabled = True
        dgvBase.ContextMenuStrip = cmsGL
        If (lblRev.Text = "-") Then
            lblRev.Text = "A"
        Else
            Dim ascii As Integer = Asc(lblRev.Text)
            lblRev.Text = Chr(ascii + 1)
        End If
    End Sub

    Private Sub tsSave_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsSaveClick
        If (validateForm()) Then
            Dim PriceType As String = "0"
            If (ckbExworks.Checked) Then PriceType = "1"
            Dim x As Array = txtQuotationNumber.Text.Split("-")
            Dim Payment As String = ""
            If (ckbExworks.Checked) Then Payment = cmbPayment.Text
            EntryID = dbSales.SaveQuotation(x(0).ToString(), _
                                            dtDocDate.Value.ToString(Var.DateFormat), _
                                            txtCustCode.Text, _
                                            txtOffice.Text, _
                                            txtPhone.Text, _
                                            txtFax.Text, _
                                            cmbAttSolut.Text, _
                                            txtAttentionname.Text, _
                                            txtEmail.Text, _
                                            dtValDate.Value.ToString(Var.DateFormat), _
                                            cbDocCurr.Text, _
                                            TypeAct, _
                                            CDec(lblSubTotalAmount.Text), _
                                            txtRef.Text, _
                                            dtRef.Value.ToString(Var.DateFormat), _
                                            cmbIncoterms.Text, _
                                            txtPaymentDay.Text, _
                                            MDI.LoginUserName, _
                                            PriceType, _
                                            Payment, _
                                            lblRev.Text)

            Dim Seq As Integer
            Dim status As Boolean = True
            If (EntryID <> "failed") Then
                For i = 0 To dgvBase.Rows.Count - 2
                    If (status) Then
                        If (dgvBase.Rows(i).Cells("clChoose").Value.ToString() <> "") Then
                            Seq = i + 1
                            Dim Notes As String = ""
                            If (dgvBase.Rows(i).Cells("clComment").Value Is Nothing) Then
                                Notes = ""
                            Else
                                Notes = dgvBase.Rows(i).Cells("clComment").Value.ToString()
                            End If
                            Dim GroupCode As Array = dgvBase.Rows(i).Cells("clChoose").Value.ToString().Split("-")
                            status = dbSales.SaveQuotationLine(EntryID, _
                                                               dtDocDate.Value.ToString(Var.DateFormat), _
                                                               txtCustCode.Text, _
                                                               GroupCode(0), _
                                                               GroupCode(1), _
                                                               "**", _
                                                               dgvBase.Rows(i).Cells("clDesc").Value.ToString(), _
                                                               cbDocCurr.Text, _
                                                               dgvBase.Rows(i).Cells("clPriceList").Value.ToString(), _
                                                               dgvBase.Rows(i).Cells("clDisc").Value.ToString(), _
                                                               dgvBase.Rows(i).Cells("clNetPrice").Value.ToString(), _
                                                               dgvBase.Rows(i).Cells("clUOM").Value.ToString(), _
                                                               dgvBase.Rows(i).Cells("clQty").Value.ToString(), _
                                                               dgvBase.Rows(i).Cells("clNetAmount").Value.ToString(), _
                                                               Notes, _
                                                               Seq, _
                                                               MDI.LoginUserName)

                        End If
                    End If
                Next
                If (status) Then
                    frmCtrl.openChild(frmQuotationList, Me.ParentForm)
                Else
                    MessageBox.Show("Saving Quotation " + EntryID + " , Failed at Seq" + Seq.ToString())
                End If
            Else
                MessageBox.Show("Saving Quotation Failed")
            End If
        End If
    End Sub

    Private Sub tsPrint_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsPrintClick
        'Dim journalCode As Array = EntryID.Split("-")
        'Dim JournalNo As Array = journalCode(1).ToString().Split("/")
        'Dim dsReport As DataSet = New dbReport().GenerateJournalReport(journalCode(0).ToString().Trim(), JournalNo(1).ToString().Trim(), "", JournalNo(0).ToString().Trim(), JournalNo(0).ToString().Trim())
        'If (dsReport IsNot Nothing) Then
        '    Dim frmViewReport As New ViewReport
        '    frmViewReport.strReport = "Journal"
        '    frmViewReport.dsReport = dsReport
        '    frmViewReport.Show()
        'End If
    End Sub

    Private Sub tsRefresh_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsRefreshClick
        Dim OpenForm As New frmQuotationEntry
        OpenForm.EntryID = EntryID
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsCancel_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsCancelClick
        Dim OpenForm As New frmQuotationEntry
        OpenForm.EntryID = EntryID
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsApprove_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsApproveClick
        If (EntryID.Trim() <> "") Then
            gbApprove.Visible = True
            pnlBase.Enabled = False
        Else : MessageBox.Show("Please Choose Quotation")
        End If
    End Sub
    ''================================== Control Header [End] ==============================================''

    <System.Diagnostics.DebuggerStepThrough()> _
    Function IsHeaderButtonCell(ByVal GridView As DataGridView, ByVal e As DataGridViewCellEventArgs) As Boolean
        Return TypeOf GridView.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso Not e.RowIndex = -1
    End Function

    Private Sub dgvBase_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBase.CellClick
        If (txtQuotationNumber.Text <> "" And cbDocCurr.Text <> "" And txtDocRate.Text <> "" And dgvBase.ReadOnly = False) Then
            If (IsHeaderButtonCell(dgvBase, e)) Then
                Dim formFind As New frmFind
                formFind.lblTitle.Text = "Search : Item Code"
                formFind.QueryHeader = "SELECT GROUPS + '-' + CODE 'ID',IC_DESCRIPTION 'Name' From SALES_PRICE WITH(NOLOCK)"
                formFind.StartPosition = FormStartPosition.CenterScreen
                formFind.type = "cell"
                formFind.dgCellValue1 = dgvBase.Rows(e.RowIndex).Cells("clChoose")
                formFind.dgCellValue2 = dgvBase.Rows(e.RowIndex).Cells("clDesc")
                formFind.Show()
                MDI.Enabled = False
            End If
        End If
    End Sub

    Private Sub dgvBase_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBase.CellValueChanged
        If (ca <> "LOAD") Then
            If (dgvBase.Rows.Count > 0) Then
                If (e.RowIndex > -1) Then
                    Select Case e.ColumnIndex
                        Case 0
                            Dim dvItem As DataView = New DataView(dsItem.Tables(0))
                            dvItem.RowFilter = "[GROUPS] + '-' + [CODE] = '" & dgvBase.Rows(e.RowIndex).Cells("clChoose").Value & "'"
                            Dim curr As String
                            If (ckbExworks.Checked) Then
                                dgvBase.Rows(e.RowIndex).Cells("clPriceList").Value = toN4(dvItem.Item(0).Row("PRICE1").ToString())
                                curr = dvItem.Item(0).Row("EXW_CURR").ToString()
                            Else
                                dgvBase.Rows(e.RowIndex).Cells("clPriceList").Value = toN4(dvItem.Item(0).Row("PRICE").ToString())
                                curr = dvItem.Item(0).Row("CURR_BASE").ToString()
                            End If
                            dgvBase.Rows(e.RowIndex).Cells("clDisc").Value = "0.00"
                            dgvBase.Rows(e.RowIndex).Cells("clUOM").Value = dvItem.Item(0).Row("UOM").ToString()
                            dgvBase.Rows(e.RowIndex).Cells("clQty").Value = "0"
                        Case 3
                            If (dgvBase.Rows(e.RowIndex).Cells("clChoose").Value <> "") Then
                                dgvBase.Rows(e.RowIndex).Cells("clDiscReal").Value = dgvBase.Rows(e.RowIndex).Cells("clDisc").Value
                                If (dgvBase.Rows(e.RowIndex).Cells("clDisc").Value <> "0") Then
                                    Dim disc As Decimal = CDec(dgvBase.Rows(e.RowIndex).Cells("clPriceList").Value) * (CDec(dgvBase.Rows(e.RowIndex).Cells("clDiscReal").Value) / 100)
                                    dgvBase.Rows(e.RowIndex).Cells("clNetReal").Value = (CDec(dgvBase.Rows(e.RowIndex).Cells("clPriceList").Value) - disc)
                                    dgvBase.Rows(e.RowIndex).Cells("clNetPrice").Value = toN4(CDec(dgvBase.Rows(e.RowIndex).Cells("clPriceList").Value) - disc)
                                Else
                                    dgvBase.Rows(e.RowIndex).Cells("clNetReal").Value = "0.00"
                                    dgvBase.Rows(e.RowIndex).Cells("clNetPrice").Value = "0.00"
                                End If
                                dgvBase.Rows(e.RowIndex).Cells("clNetAmount").Value = toN4(CDec(dgvBase.Rows(e.RowIndex).Cells("clQty").Value) * CDec(dgvBase.Rows(e.RowIndex).Cells("clNetPrice").Value))
                            End If
                        Case 4
                            If (dgvBase.Rows(e.RowIndex).Cells("clChoose").Value <> "") Then
                                dgvBase.Rows(e.RowIndex).Cells("clNetReal").Value = dgvBase.Rows(e.RowIndex).Cells("clNetPrice").Value
                                If (dgvBase.Rows(e.RowIndex).Cells("clNetPrice").Value <> "0") Then
                                    Dim disc As Decimal
                                    If (CDec(dgvBase.Rows(e.RowIndex).Cells("clPricelist").Value) <> 0) Then
                                        disc = (CDec(dgvBase.Rows(e.RowIndex).Cells("clNetReal").Value) / CDec(dgvBase.Rows(e.RowIndex).Cells("clPricelist").Value)) * 100
                                    Else : disc = 0
                                    End If
                                    dgvBase.Rows(e.RowIndex).Cells("clDiscReal").Value = (100 - disc)
                                    dgvBase.Rows(e.RowIndex).Cells("clDisc").Value = toN4(100 - disc)
                                Else
                                    dgvBase.Rows(e.RowIndex).Cells("clDiscReal").Value = "0.00"
                                    dgvBase.Rows(e.RowIndex).Cells("clDisc").Value = "0.00"
                                End If
                                dgvBase.Rows(e.RowIndex).Cells("clNetAmount").Value = toN4(CDec(dgvBase.Rows(e.RowIndex).Cells("clQty").Value) * CDec(dgvBase.Rows(e.RowIndex).Cells("clNetPrice").Value))
                            End If
                        Case 6
                            dgvBase.Rows(e.RowIndex).Cells("clNetAmount").Value = toN4(CDec(dgvBase.Rows(e.RowIndex).Cells("clQty").Value) * CDec(dgvBase.Rows(e.RowIndex).Cells("clNetPrice").Value))
                    End Select
                End If
            End If
            SumSubTotal()
        End If
    End Sub

    Private Sub SumSubTotal()
        Dim subTotal As Decimal = 0
        Dim ct As Integer = 0
        For i = 0 To dgvBase.Rows.Count - 1
            Try
                If (dgvBase.Rows(i).Cells("clNetAmount").Value = "" Or IsNumeric(dgvBase.Rows(i).Cells("clNetAmount").Value) = False) Then
                    dgvBase.Rows(i).Cells("clNetAmount").Value = "0"
                End If
                If (Convert.ToDecimal(dgvBase.Rows(i).Cells("clNetAmount").Value) < 0) Then
                    MessageBox.Show("Amount can't minus")
                    dgvBase.Rows(i).Cells("clNetAmount").Value = "0"
                End If
                If (dgvBase.Rows(i).Cells("clChoose").Value.ToString() <> "") Then
                    subTotal += Convert.ToDecimal(dgvBase.Rows(i).Cells("clNetAmount").Value)
                    dgvBase.Rows(i).Cells("clNetAmount").Value = curr2word.dec2curr(CDec(dgvBase.Rows(i).Cells("clNetAmount").Value))
                    ct += 1
                End If
            Catch ex As Exception

            End Try
        Next
        If (ct = dgvBase.Rows.Count) Then
            dgvBase.Rows.Add(1)
            If (dgvBase.ReadOnly = False) Then
                ToolbarHeader1.ActionCtrl(False, False, False, False, False, True, True, False, True)
                dgvBase.ContextMenuStrip = cmsGL
            End If
        End If
        lblSubTotalAmount.Text = curr2word.dec2curr(subTotal)
    End Sub

    Private Sub dtDocDate_ValueChanged(sender As Object, e As EventArgs) Handles dtDocDate.ValueChanged, dtValDate.ValueChanged, dtRef.ValueChanged, dtPOCode.ValueChanged
        If (EntryID = "") Then
            txtQuotationNumber.Text = dbSales.LastNumberQuotation(dtDocDate.Value.ToString("yyyy"))
        End If
    End Sub

    Private Sub ckbExworks_CheckedChanged(sender As Object, e As EventArgs) Handles ckbExworks.CheckedChanged
        pnlExwork.Enabled = ckbExworks.Checked
    End Sub

    Private Sub cmsGL_Click(sender As Object, e As EventArgs) Handles cmsGL.Click
        Dim rowCount As Integer = dgvBase.RowCount
        If (rowCount > 1) Then
            Dim rowI As Integer = dgvBase.CurrentRow.Index
            dgvBase.Rows.RemoveAt(rowI)
            SumSubTotal()
        End If
    End Sub

    Private Sub dgvBase_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvBase.CellMouseDown
        If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex >= 0 Then
            dgvBase.ClearSelection()
            dgvBase.CurrentCell = dgvBase.Rows(e.RowIndex).Cells(0)
            dgvBase.Rows(e.RowIndex).Selected = True
        End If
    End Sub

    Private Sub cbDocCurr_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbDocCurr.SelectedIndexChanged
        If (cbDocCurr.Text <> "") Then
            lblPackingCurr.Text = cbDocCurr.Text
            lblDeliveryCurr.Text = cbDocCurr.Text
            lblSubTotalCurr.Text = cbDocCurr.Text
            Dim dvCurr As DataView = New DataView(dsCurr.Tables(0))
            dvCurr.RowFilter = "[ID] = '" & cbDocCurr.SelectedItem.ToString() & "'"
            CurrBase = dvCurr.Item(0).Row("CurrBase").ToString()
            txtDocRate.Text = curr2word.dec2curr(dvCurr.Item(0).Row("CurrRate").ToString())
        End If
    End Sub

    Private Sub txtN2_Leave(sender As Object, e As EventArgs) Handles txtPackingCost.Leave, txtDeliveryCost.Leave, txtDocRate.Leave, txtVolume.Leave, txtWeight.Leave
        Dim txt As TextBox = sender
        If (IsNumeric(txt.Text)) Then
            txt.Text = curr2word.dec2curr(txt.Text)
        End If
    End Sub

    Private Sub txtN0_Leave(sender As Object, e As EventArgs) Handles txtPaymentDay.Leave
        Dim txt As TextBox = sender
        If (IsNumeric(txt.Text)) Then
            txt.Text = toN0(txt.Text)
        End If
    End Sub

    Private Sub txtCurr_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtPackingCost.Validating, txtDeliveryCost.Validating, txtDocRate.Validating, txtPaymentDay.Validating, txtVolume.Validating, txtWeight.Validating
        Dim txt As TextBox = sender
        If (txt.Text.Trim() <> "") Then
            If (IsNumeric(txt.Text) = False) Then
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub txtCurr_Enter(sender As Object, e As EventArgs) Handles txtPackingCost.Enter, txtDeliveryCost.Enter, txtDocRate.Enter, txtPaymentDay.Enter, txtVolume.Enter, txtWeight.Enter
        Dim txt As TextBox = sender
        If (IsNumeric(txt.Text)) Then
            txt.Text = Convert.ToDecimal(txt.Text).ToString()
            BeginInvoke(DirectCast(Sub() txt.SelectAll(), Action))
        End If
    End Sub

    Private Sub txtCurr_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtPackingCost.KeyPress, txtDeliveryCost.KeyPress, txtDocRate.KeyPress, txtPaymentDay.KeyPress, txtVolume.KeyPress, txtWeight.KeyPress
        Dim txt As TextBox = sender
        Dim FullStop As Char
        FullStop = "."
        If e.KeyChar = FullStop And txt.Text.IndexOf(FullStop) <> -1 Then
            e.Handled = True
            Return
        End If
        If Not Char.IsDigit(e.KeyChar) Then
            If (e.KeyChar <> FullStop) And
               (e.KeyChar <> Convert.ToChar(Keys.Back)) Then
                e.Handled = True
                Return
            End If
        End If
    End Sub

    Private Function toN0(txt As String) As String
        If (IsNumeric(txt) = False) Then txt = "0"
        Return Convert.ToDecimal(txt).ToString("N0", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
    End Function

    Private Function toN4(txt As String) As String
        If (IsNumeric(txt) = False) Then txt = "0"
        Return Convert.ToDecimal(txt).ToString("N4", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))
    End Function

    Private Sub btnSearchPhone_Click(sender As Object, e As EventArgs) Handles btnSearchPhone.Click
        If (txtCustCompany.Text <> "") Then
            Dim formFind As New frmFind
            formFind.lblTitle.Text = "Search : GL Journal Group"
            formFind.QueryHeader = "SELECT Office, Addr, Phone, Fax FROM vCustomer WHERE code = " + txtCustCode.Text
            formFind.StartPosition = FormStartPosition.CenterScreen
            formFind.type = "txt"
            formFind.txtValue = txtOffice
            formFind.Show()
            MDI.Enabled = False
        End If
    End Sub

    Private Sub btnSearchAttention_Click(sender As Object, e As EventArgs) Handles btnSearchAttention.Click
        If (txtCustCompany.Text <> "" And txtOffice.Text <> "") Then
            Dim formFind As New frmFind
            formFind.lblTitle.Text = "Search : GL Journal Group"
            formFind.QueryHeader = "SELECT CCID_SEQ_NUMBER [SEQ], SALUTATION [Salutation], CCID_CONTACT_NAME [Full Name], CCID_POSITION [Position], CCID_EMAIL [Email] FROM CUSTOMER_CONTACT WHERE CUSTOMER_CODE = '" & txtCustCode.Text & "' AND CUST_OFF_MNG = '" & txtOffice.Text & "' AND CCID_CONTACT_NAME IS NOT NULL"
            formFind.StartPosition = FormStartPosition.CenterScreen
            formFind.type = "txt"
            formFind.txtValue = txtSeq
            formFind.Show()
            MDI.Enabled = False
        End If
    End Sub

    Private Sub txtCustCode_TextChanged(sender As Object, e As EventArgs) Handles txtCustCode.TextChanged
        advCustomer.Visible = False
        txtOffice.Text = ""
        txtSeq.Text = ""
        txtPhone.Text = ""
        txtFax.Text = ""
        txtAttentionname.Text = ""
        cmbAttSolut.Text = ""
        txtEmail.Text = ""
        If (txtCustCode.Text = "load") Then
            txtCustCode.Text = advCustomer.dsResult.Tables(0).Rows(0)("Code").ToString()
        ElseIf (txtCustCode.Text.Trim() <> "load") Then
            Dim dv As DataView = New DataView(dsCustomer.Tables(0))
            dv.RowFilter = "[Code] = '" & txtCustCode.Text.Trim() & "'"
            txtCustCompany.Text = dv.Item(0).Row("Company").ToString()
            txtPaymentDay.Text = dv.Item(0).Row("Term Day").ToString()
            txtOffice.Text = "HQ"
        Else
            txtCustCompany.Text = ""
        End If
    End Sub

    Private Sub ShowAdvCustomer_DoubleClick(sender As Object, e As EventArgs) Handles txtCustCode.DoubleClick, txtCustCompany.DoubleClick
        advCustomer.Visible = True
        advCustomer.BringToFront()
        advCustomer._Show()
    End Sub

    Private Sub txtOffice_TextChanged(sender As Object, e As EventArgs) Handles txtOffice.TextChanged
        If (txtOffice.Text.Trim().Length > 0) Then
            Dim dtPhone As DataTable = New dbSystem().FreeQueryDataTable("SELECT Phone, Fax FROM vCustomer WHERE code = '" & txtCustCode.Text & "' AND office = '" & txtOffice.Text & "'")
            If (dtPhone.Rows.Count > 0) Then
                txtPhone.Text = dtPhone.Rows(0)("Phone").ToString().Trim()
                txtFax.Text = dtPhone.Rows(0)("Fax").ToString().Trim()
            Else
                txtPhone.Text = ""
                txtFax.Text = ""
            End If
            txtSeq.Text = ""
            Dim dtContact As DataTable = New dbSystem().FreeQueryDataTable("SELECT TOP 1 CCID_SEQ_NUMBER, SALUTATION, CCID_CONTACT_NAME, CCID_EMAIL FROM CUSTOMER_CONTACT WHERE CUSTOMER_CODE = '" & txtCustCode.Text & "' AND CUST_OFF_MNG = '" & txtOffice.Text & "' AND CCID_CONTACT_NAME IS NOT NULL")
            If (dtContact.Rows.Count > 0) Then
                txtSeq.Text = dtContact.Rows(0)("CCID_SEQ_NUMBER").ToString().Trim()
                'cmbAttSolut.Text = dtContact.Rows(0)("SALUTATION").ToString().Trim()
                'txtAttentionname.Text = dtContact.Rows(0)("CCID_CONTACT_NAME").ToString().Trim()
                'txtEmail.Text = dtContact.Rows(0)("CCID_EMAIL").ToString().Trim()
            Else
                txtSeq.Text = ""
                'cmbAttSolut.Text = ""
                'txtAttentionname.Text = ""
                'txtEmail.Text = ""
            End If
        Else
            txtPhone.Text = ""
            txtFax.Text = ""
            txtAttentionname.Text = ""
            cmbAttSolut.Text = ""
            txtEmail.Text = ""
        End If
    End Sub

    Private Sub txtSeq_TextChanged(sender As Object, e As EventArgs) Handles txtSeq.TextChanged
        If (txtSeq.Text.Trim().Length > 0) Then
            Dim dtContact As DataTable = New dbSystem().FreeQueryDataTable("SELECT TOP 1 SALUTATION, CCID_CONTACT_NAME, CCID_EMAIL FROM CUSTOMER_CONTACT WHERE CUSTOMER_CODE = '" & txtCustCode.Text & "' AND CUST_OFF_MNG = '" & txtOffice.Text & "' AND CCID_SEQ_NUMBER = '" & txtSeq.Text & "' AND CCID_CONTACT_NAME IS NOT NULL")
            If (dtContact.Rows.Count > 0) Then
                cmbAttSolut.Text = dtContact.Rows(0)("SALUTATION").ToString().Trim()
                txtAttentionname.Text = dtContact.Rows(0)("CCID_CONTACT_NAME").ToString().Trim()
                txtEmail.Text = dtContact.Rows(0)("CCID_EMAIL").ToString().Trim()
            Else
                cmbAttSolut.Text = ""
                txtAttentionname.Text = ""
                txtEmail.Text = ""
            End If
        Else
            txtAttentionname.Text = ""
            cmbAttSolut.Text = ""
            txtEmail.Text = ""
        End If
    End Sub

    Private Sub btnApprove_Click(sender As Object, e As EventArgs) Handles btnApprove.Click
        If (txtPOCode.Text.Trim().Length > 0) Then
            Dim status As String = dbSales.TransactionSalesManage(EntryID, txtPOCode.Text, dtPOCode.Value.ToString(Var.DateFormat), DBNull.Value, DBNull.Value)
            Dim OpenForm As New frmQuotationEntry
            OpenForm.EntryID = EntryID
            frmCtrl.OpenFormDetail(Me, OpenForm)
        Else
            pnlBase.Enabled = True
            gbApprove.Visible = False
        End If
    End Sub
End Class